/**
 * Copyright 2007-2010 非也
 * All rights reserved. 
 * 
 * This library is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License v3 as published by the Free Software
 * Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with this library; if not, see http://www.gnu.org/licenses/lgpl.html.
 *
 */
package org.fireflow2.designer.eclipse.figures.widget;

import org.eclipse.draw2d.ChopboxAnchor;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.fireflow2.designer.eclipse.figures.CommonFigureInterface;

/**
 *
 * @author 非也 nychen2000@163.com
 * Fire Workflow 官方网站：www.firesoa.com 或者 www.fireflow.org
 *
 */
public class RouterAnchor  extends ChopboxAnchor{
	public RouterAnchor(IFigure owner){
		super(owner);
	}
	protected Rectangle getBox() {
		CommonFigureInterface figure = (CommonFigureInterface)this.getOwner();
		
		return figure.getBox();
	}
	public Point getLocation(Point reference) {		
		org.eclipse.draw2d.geometry.Rectangle r = org.eclipse.draw2d.geometry.Rectangle.SINGLETON;
		r.setBounds(getBox());
		
		r.translate(-1, -1);
		r.resize(1, 1);

		getOwner().translateToAbsolute(r);
		float centerX = r.x + 0.5f * r.width;
		float centerY = r.y + 0.5f * r.height;

		if (r.isEmpty()
				|| (reference.x == (int) centerX && reference.y == (int) centerY))
			return new Point((int) centerX, (int) centerY); // This avoids
															// divide-by-zero
		
		
		float dx = reference.x - centerX;
		float dy = reference.y - centerY;
		
		if (dy==0){
			return new Point(Math.round(centerX+dx),centerY);
		}
		
		float scale = Math.abs(dx/dy);
		float ddy = 0.5f*r.width / (scale+1);
		float ddx = Math.abs(scale*ddy);
		
		if (dx>=0 && dy>=0){
			return new Point(centerX+ddx,centerY+ddy);
		}
		else if (dx<=0 && dy<=0){
			return new Point(centerX-ddx,centerY-ddy);
		}
		else if (dx>=0 && dy<=0){
			return new Point(centerX+ddx,centerY-ddy);
		}
		else {
			return new Point(centerX-ddx,centerY+ddy);
		}

	}

}
